package model

import (
	"errors"
	"time"
)

type Message struct {
	Id        int64
	Uid       int64
	CreatedAt time.Time `xorm:"created"`
	Enable    bool
	Public    bool
	Author    string
	Title     string
	Content   string `xorm:"text"` // saved via markdown
}

func (m *Message) OneById() error {
	ok, err := orm.ID(m.Id).Get(m)
	if !ok {
		return errors.New(MessageNotFound)
	}
	return err
}

func (m *Message) Page(num, size int32, desc bool, order string) ([]Message, error) {
	length := int(size)
	start := (int(num) - 1) * length
	if length == 0 {
		length = 5
	}
	var messages []Message
	o := orm.Limit(length, start)
	if order == "" {
		order = "id"
	}
	if m.Enable {
		o.Where("enable = ?", true)
	}
	if m.Uid > 0 {
		o.And("uid = ?", m.Uid)
	} else {
		o.And("public = ?", true)
	}
	//if m.Public {
	//	o.And("public = ?", true)
	//}
	if desc {
		o.Desc(order)
	} else {
		o.Asc(order)
	}
	err := o.Find(&messages)
	return messages, err
}

func (m *Message) Count() (int64, error) {
	o := orm.Where("id > ?", 0)
	if m.Enable {
		o = o.And("enable = ?", true)
	}
	if m.Public {
		o.And("public = ?", true)
	}
	if m.Uid > 0 {
		o.And("uid = ?", m.Uid)
	}
	return o.Count(m)
}

func (m *Message) Create() error {
	ok, err := orm.Insert(m)
	if ok == 0 {
		return errors.New(MessageCreateFailed)
	}
	return err
}

func (m *Message) EnableCheck() error {
	if !m.Enable {
		return errors.New(MessageDisabled)
	}
	return nil
}

func (m *Message) Toggle() error {
	m.Enable = !m.Enable
	ok, err := orm.ID(m.Id).Cols("enable").Update(m)
	if ok == 0 {
		return errors.New(MessageEditFailed)
	}
	return err
}
